package com.tjnu.losca.utils;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Losca
 * @date 2022/3/27 17:25
 */
@Component
public class FileUtils {
    @Value("${file.minio.url}")
    private String minioUrl;
    @Value("${file.minio.username}")
    private String minioUsername;
    @Value("${file.minio.password}")
    private String minioPassword;
    public String imgUpload(MultipartFile file) throws Exception {
        //获取文件大小
        long size = file.getSize();
        //获取文件后缀名
        String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
        MinioClient minioClient = new MinioClient(minioUrl, minioUsername, minioPassword);
        PutObjectOptions options = new PutObjectOptions(size, 0);
        //设置文件格式，图片能够被在线预览
        options.setContentType(file.getContentType());
        StringBuilder builder = new StringBuilder();
        //生成文件名 时间戳+随机数
        builder.append(System.currentTimeMillis() + RandomStringUtils.random(6, false, true));
        //生成文件名后缀
        builder.append(".").append(suffix);
        // 使用putObject上传一个文件到存储桶中。
        minioClient.putObject("img", builder.toString(), file.getInputStream(), options);
        return builder.toString();
    }

}
